package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 连接EMQX消息中间件的配置类
 */
@Slf4j
@Configuration
public class MqttConfiguration {
  @Autowired
  private MqttContext mqttContext;
    private String host = "tcp://localhost:1883";

    private String username = "admin";
    private String password = "public";

    private String clientId = "order_service_client" + Math.random();

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient mqttClient = new MqttClient( host,clientId);

        MqttConnectOptions options = new MqttConnectOptions();

        options.setUserName(username);
        options.setPassword(password.toCharArray());

    /*
        //清session
        options.setCleanSession(true);
        //心跳  保持活跃的时间
        options.setKeepAliveInterval(60);
        //连接的超时
        options.setConnectionTimeout(30);
        options.setMaxInflight(100);
        //自动重连
        options.setAutomaticReconnect(true);
        //执行的一个时间超时
        options.setExecutorServiceTimeout(1000);
*/
        options.setAutomaticReconnect(true); //断开了自动重连
        //把mqttConsumer放到容器里面，mqttClient是不知道的，所以必须new MqttConsumer()一个放到
        // mqttClient.setCallback(); 这是规定
        //MqttConsumer 是通过java new 创建出来的， 没有在spring容器中管理
        // 1 通过构造方法 把MqttClient对象传进去
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient,mqttContext);
        //2 通过setter方法 把MqttClient对象设置进去
        //mqttConsumer.setMqttClient(mqttClient);
        mqttClient.setCallback(mqttConsumer);

        //通过配置和EMQX进行连接  回调函数
        //调这个方法的时候试着与EMQX去连接，但是现在连接成功还是不成功不知道，如果订单向知道，就设置一个回调
        mqttClient.connect(options);
        log.debug("MQTT客户端和EMQX连接，是否连接成功不知道，连接成功的结果是通过Callback回调"+"来通知订单服务中的MqttConsumer");
        //以上代码是异步执行的
        return  mqttClient;
    }
}
